package com.zynn.count.util;

import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;

/**
 * @author Admin
 */
public class HttpUtil {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param path   发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String path, String params) {
        if (StringUtils.isNotEmpty(params)) {
            path += "?" + params;
        }
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            InputStream inStream = conn.getInputStream();
            byte[] data = StreamTool.readInputStream(inStream);
            return new String(data, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param path   发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String path, String params) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 提交模式
            conn.setRequestMethod("POST");
            //连接超时 单位毫秒
            conn.setConnectTimeout(5000);
            // 是否输入参数
            conn.setDoOutput(true);
            byte[] bypes = params.getBytes("UTF-8");
            // 输入参数
            conn.getOutputStream().write(bypes);
            InputStream inStream = conn.getInputStream();
            byte[] data = StreamTool.readInputStream(inStream);
            return new String(data, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 异步发送post请求
     *
     * @param path   请求路径
     * @param params 请求参数
     * @return string
     */
    public static String asynSendPost(String path, String params) {
        Callable<String> callable = () -> sendPost(path, params);
        try {
            return callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 异步发送get请求
     *
     * @param path   路径
     * @param params 请求参数
     * @return string
     */
    public static String asynSendGet(String path, String params) {
        Callable<String> callable = () -> sendGet(path, params);
        try {
            return callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
